#!/bin/bash
# -*- coding: utf-8 -*-
# @File    : cuit_network.sh
# @Time    : 2023/7/28 17:31
# @Author  : Zhong Xiao Wei
# @EMAIL   : kura_lee@163.com

#### 用户配置文件 #############
# 账号
username=''
# 密码
password=''
# 运营商配置 填对应字符串 移动：'%25E7%25A7%25BB%25E5%258A%25A8' 联通：'%25E8%2581%2594%25E9%2580%259A' 电信：'%25E7%2594%25B5%25E4%25BF%25A1' 校园网：'%25E6%25A0%25A1%25E5%259B%25AD%25E7%25BD%2591'
isp='%25E7%2594%25B5%25E4%25BF%25A1'
########################################################################################################

#### cuit站点配置 #############
url='http://10.254.241.19/'
login_url='http://10.254.241.19/eportal/InterFace.do?method=login'
logout_url='http://10.254.241.19/eportal/InterFace.do?method=logout'
online_info_url='http://10.254.241.19/eportal/InterFace.do?method=getOnlineUserInfo'
header='User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
#########################################################################################################

# 登录
if [[ $# -eq 0 ]] || [[ $# -eq 1 && "$1" == "login" ]]; then
    # 获取查询字符串
    urlRes=$(curl -L ${url})
    if echo "$urlRes" | grep -q "^<!DOCTYPE"; then
        echo 已经登录,无需再次登录！
        exit -1
    elif echo "$urlRes" | grep -q "^<script>"; then
        query_str=$(echo "${urlRes}" | grep -o '\?.*' | cut -c2- | cut -d \' -f1) 
        echo 成功获取登录查询字符串...
    else
        echo "error:获取查询字符串错误，请检查网络连接状态！"
        exit -1
    fi
    # 将查询字符串query_str中的&替换为encodeURIComponent其编码%26保证data输入参数queryString被curl解析为一个参数
    encodeQueryString=${query_str//&/%26}
    # post登录数据拼接
    data="userId=${username}&password=${password}&service=${isp}&queryString=${encodeQueryString}&\
    operatorPwd=&operatorUserId=&validcode=&passwordEncrypt=false"
    echo 正在执行登录...
    count=0
    while [[ $count -lt 10 ]];do
        response=$(curl -H "${header}" -d "${data}" -L "${login_url}")
        result=$(echo "$response" | sed -n 's/.*"result"\s*:\s*"\([^"]*\)".*/\1/p')  
        message=$(echo "$response" | sed -n 's/.*"message"\s*:\s*"\([^"]*\)".*/\1/p')
        if [[ ${result} = "success" ]];then
            echo 登录成功！
            break
        else 
            echo 登录错误,message:${message}
        fi
        let count=count+1
        echo 开始第${count}次重新登录...
        sleep 1
    done
    if [[ ${result} != "success" ]];then
        echo 最后一次失败响应message:${message}
        echo 登录失败,请检查配置后重试！！！
    fi
# 登出
elif [[ $# -eq 1 && "$1" == "logout" ]]; then
    response=$(curl -H "${header}" -d "userIndex=" -L "${online_info_url}")
    result=$(echo "$response" | sed -n 's/.*"result"\s*:\s*"\([^"]*\)".*/\1/p')  
    if [[ ${result} != "fail" ]];then
        echo $(echo `curl -L ${logout_url}` | sed -n 's/.*"message"\s*:\s*"\([^"]*\)".*/\1/p')
    else 
        echo 用户已不在线!!!
    fi
else
  echo "用法: $0 [login|logout]"
  exit 1
fi
